# 配置 Django 环境
import os
import sys

# reset root
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.chdir(root_dir)
sys.path.append(root_dir)

# setup
from django.utils import timezone
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aiops_backend.settings")
django.setup()

from api.models import User, Role, RelationUserRole


def create_admin():
    if not User.objects.filter(username="aiops@admin").exists():
        user = User.objects.create(
            username="aiops@admin",
            password="nkcs@aiops",
            phone="",
            email="",
            department="系统管理",
            description="",
            create_time=timezone.now(),
            last_edit_time=timezone.now(),
        )
        RelationUserRole.objects.create(user_id=user.id, role_id=1)


def create_default_role():
    if not Role.objects.filter(code="admin").exists():
        Role.objects.create(
            level=1,
            name="admin",
            code="admin",
            description="管理员",
            create_time=timezone.now(),
            last_edit_time=timezone.now(),
            fault_injection=True,
            data_monitor=True,
            detection=True,
            diagnosis=True,
            manage=True,
            RecordShow=True,
        )
    if not Role.objects.filter(code="user").exists():
        Role.objects.create(
            level=2,
            name="user",
            code="user",
            description="机构用户",
            create_time=timezone.now(),
            last_edit_time=timezone.now(),
            fault_injection=True,
            data_monitor=True,
            detection=True,
            diagnosis=True,
            manage=False,
            RecordShow=False,
        )


def create_default():
    create_default_role()
    create_admin()
    print("successfully create default")


if __name__ == "__main__":
    create_default()
    print("Done!")
